document.addEventListener('DOMContentLoaded', function() {
    const apiUrl = 'http://101.34.242.206:9990/Blogs/get';
    const searchApiUrl = 'http://101.34.242.206:9990/Blogs/getByKeyword';
    const labelApiUrl = 'http://101.34.242.206:9990/Blogs/getBlogByLabel';
    const commentsApiUrl = 'http://101.34.242.206:9990/Comments/getNewComments';
    let currentPage = 1;
    const pageSize = 3;
    let currentLabel = '';

    function fetchUserInfo() {
        fetch('http://101.34.242.206:9990/users/queryCurrentUserInfo')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    document.getElementById('nickname').textContent = data.data.nickname;
                    document.getElementById('avatar').src = data.data.headerurl;
                } else {
                    alert('您还未登录！');
                }
            })
            .catch(error => {
                console.error('Error fetching user data:', error);
                alert('您还未登录！');
            });
    }

    function fetchBlogs(pageNum) {
        const url = currentLabel ? `${labelApiUrl}?label=${encodeURIComponent(currentLabel)}&pageNum=${pageNum}&pageSize=${pageSize}` : `${apiUrl}?pageNum=${pageNum}&pageSize=${pageSize}`;
        console.log('Fetching blogs from URL:', url); // 添加日志

        fetch(url)
            .then(response => {
                console.log('Response received:', response); // 添加日志
                return response.json();
            })
            .then(data => {
                console.log('Data received:', data); // 添加日志
                if (data.code === 200) {
                    displayBlogs(data.data.blogs);
                    setupPagination(data.data.totalcount || data.data.total, pageNum);
                }
            })
            .catch(error => console.error('Error fetching blogs:', error));
    }

    function fetchBlogsByKeyword(keyword, pageNum) {
        const url = `${searchApiUrl}?keyword=${encodeURIComponent(keyword)}&pageNum=${pageNum}&pageSize=${pageSize}`;
        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    displayBlogs(data.data.blogs);
                    setupPagination(data.data.totalcount || data.data.total, pageNum);
                }
            })
            .catch(error => console.error('Error fetching blogs:', error));
    }

    function fetchComments() {
        fetch(commentsApiUrl)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    displayComments(data.data);
                } else {
                    console.error('Failed to fetch comments:', data.message);
                }
            })
            .catch(error => console.error('Error fetching comments:', error));
    }

    function displayBlogs(blogs) {
        const articlesContainer = document.querySelector('.articles');
        articlesContainer.innerHTML = '';

        blogs.forEach(blog => {
            const articleElement = document.createElement('div');
            articleElement.className = 'article';
            articleElement.setAttribute('data-id', blog.id);

            articleElement.innerHTML = `
                <img src="${blog.coverurl}" alt="Article Image">
                <div class="article-content">
                    <h2>${blog.title}</h2>
                    <p>${blog.content.substring(0, 100)}...</p>
                    <div class="meta">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-user"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                        ${blog.author}
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-calendar" style="margin-left: 10px;"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>
                        ${new Date(blog.createtime).toLocaleDateString()}
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-message-circle" style="margin-left: 10px;"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5"></path></svg>
                        ${blog.likes}条评论
                    </div>
                </div>
            `;

            articleElement.addEventListener('click', () => {
                window.location.href = `blog_detail.html?id=${blog.id}`;
            });

            articlesContainer.appendChild(articleElement);
        });
    }

    function displayComments(comments) {
        const commentsContainer = document.getElementById('commentsContainer');
        commentsContainer.innerHTML = ''; // 清空容器

        comments.forEach(comment => {
            const commentElement = document.createElement('div');
            commentElement.classList.add('comment');
            commentElement.innerHTML = `
                <img src="${comment.headerurl}" alt="${comment.nickname}" class="comment-avatar">
                <div class="comment-content">
                    <p class="comment-nickname">${comment.nickname}</p>
                    <p class="comment-text">${comment.content}</p>
                </div>
            `;
            commentsContainer.appendChild(commentElement);
        });
    }

    function setupPagination(totalCount, currentPage) {
        const paginationContainer = document.querySelector('.pagination');
        paginationContainer.innerHTML = '';

        const totalPages = Math.ceil(totalCount / pageSize);

        if (currentPage > 1) {
            const prevPage = document.createElement('a');
            prevPage.href = '#';
            prevPage.innerHTML = '&laquo;';
            prevPage.addEventListener('click', (e) => {
                e.preventDefault();
                fetchBlogs(currentPage - 1);
            });
            paginationContainer.appendChild(prevPage);
        }

        for (let i = 1; i <= totalPages; i++) {
            const pageLink = document.createElement('a');
            pageLink.href = '#';
            pageLink.textContent = i;
            pageLink.className = i === currentPage ? 'active' : '';
            pageLink.addEventListener('click', (e) => {
                e.preventDefault();
                fetchBlogs(i);
            });
            paginationContainer.appendChild(pageLink);
        }

        if (currentPage < totalPages) {
            const nextPage = document.createElement('a');
            nextPage.href = '#';
            nextPage.innerHTML = '&raquo;';
            nextPage.addEventListener('click', (e) => {
                e.preventDefault();
                fetchBlogs(currentPage + 1);
            });
            paginationContainer.appendChild(nextPage);
        }
    }

    function setupTagClickEvents() {
        const tags = document.querySelectorAll('.tags a');
        tags.forEach(tag => {
            tag.addEventListener('click', (e) => {
                e.preventDefault(); // 阻止默认行为
                currentLabel = tag.getAttribute('data-label');
                currentPage = 1;
                console.log('Tag clicked:', currentLabel); // 添加日志
                fetchBlogs(currentPage); // 调用 fetchBlogs 函数
            });
        });
    }

    document.getElementById('searchButton').addEventListener('click', () => {
        const keyword = document.getElementById('searchInput').value.trim();
        if (keyword) {
            fetchBlogsByKeyword(keyword, currentPage);
        }
    });

    document.getElementById('searchInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            const keyword = document.getElementById('searchInput').value.trim();
            if (keyword) {
                fetchBlogsByKeyword(keyword, currentPage);
            }
        }
    });

    // 初始化标签云
    if (document.getElementById('tagcanvas')) {
        try {
            TagCanvas.Start('tagcanvas', 'tags', {
                textColour: '#000000',
                outlineColour: '#ff00ff',
                reverse: true,
                depth: 0.8,
                maxSpeed: 0.05,
                outlineMethod: 'block',
                pulsateTo: 0.2,
                initial: [0.1, -0.1],
                decel: 0.98,
                hideTags: false,
                shadow: '#ccf',
                shadowBlur: 3,
                weight: true,
                fadeIn: 1000,
                activeCursor: 'pointer',
                wheelZoom: false,
                pinchZoom: true,
                freezeActive: true,
                shuffleTags: true,
                clickToFront: 600,
                textFont: 'Impact,"Arial Black",sans-serif',
                weightMode: 'both',
                weightSize: 1.0,
                weightGradient: {
                    0: '#f00', // Red
                    0.33: '#ff0', // Yellow
                    0.66: '#0f0', // Green
                    1: '#00f'  // Blue
                }
            });
        } catch(e) {
            console.log('Canvas error:', e);
            document.getElementById('tagcanvas').style.display = 'none';
        }
    }

    fetchUserInfo();
    fetchBlogs(currentPage);
    fetchComments();
    setupTagClickEvents();
});







